var goodsDetail = {};
$(function () {
    //tab切换初始化
    goodsDetail.methods.tabInit(this);
    //初始化切换
    goodsDetail.methods.sliderInit(this);
    // 固定详情评价售后保障栏
    goodsDetail.methods.columnFixed();
    //选择规格
    goodsDetail.methods.chooseSize(this);
    //数字操作
    goodsDetail.methods.chooseNum(this);
    //事件操作
    goodsDetail.addEvent(this);
    //购物车加入效果
    goodsDetail.methods.FlyCartInit(this);
    //获取地址定位
    //goodsDetail.methods.getLocation(this);
    //选择城市
    goodsDetail.methods.ChooseCity(this);
    // 选择支付单位
    goodsDetail.methods.choosePay(this);
    //放大镜效果初始化
    goodsDetail.methods.ScaleImage(this);
    // 关注
    goodsDetail.methods.isfocus(); 
    // 关注店铺
    goodsDetail.methods.isStore();
    //详情内容导航
    goodsDetail.methods.DetailNav(this);
    // 评价图片切换
    goodsDetail.methods.PictureSwitching(this);
    // 追评下拉
    goodsDetail.methods.chasingDown();
    // 追评评论
    goodsDetail.methods.reviewComment();
    // 分页
    goodsDetail.methods.pagination();

});
goodsDetail.data = {};
goodsDetail.methods = {};
goodsDetail.addEvent = function (obj) {

};
goodsDetail.methods.getLocation = function (obj) {
    var locationStr = returnCitySN.cname;
    $(".shop-position .shop-position-title").html("<span></span>" + "&nbsp;&nbsp;&nbsp;" + locationStr.substring(3));
    $(".shop-goods-delivery .shop-city-choose .shop-city-text").text(locationStr);

}
// 固定详情评价售后保障栏
goodsDetail.methods.columnFixed = function () {
    var bookDetailsScrollTop = $(".shop-details-show-nav").offset().top;
    var scrollH = 0;
    $(window).on("scroll", function () {
        scrollH = $(this).scrollTop();
        if (scrollH >= bookDetailsScrollTop) {
            $(".shop-details-show-nav-fixed").css("display", "block");
            $(".shop-details-show-nav").css({
                "position": "fixed",
                "top": 0,
                "z-index": 999,
                "margin": "0 auto",
                "margin-left": "232px"
            });
        } else if (scrollH < bookDetailsScrollTop) {
            $(".shop-details-show-nav-fixed").css("display", "none");
            $(".shop-details-show-nav").css({
                "position": "static",
                "margin": "0"
            });
        }
    })

    $(".shop-tab-nav-product-item").on("click", function () {
        $(".shop-details-show-nav-fixed").css("display", "none");
        if (scrollH >= bookDetailsScrollTop) {
            $("html,body").animate({ scrollTop: bookDetailsScrollTop }, 0);
            $(".shop-details-show-nav-fixed").css("display", "none");
        }
    })
}
//初始化tab
goodsDetail.methods.tabInit = function (obj) {
    $(".shop-tabcontrol").each(function (val) {
        var tab = new Controller.TabControl({
            container: $(this),
            tabNavItem: ".shop-tab-nav-item",
            tabConItem: ".shop-tab-con-item",
            tagName: "data-id",
            event: "click"
        });
    });

};
//初始化切换
goodsDetail.methods.sliderInit = function (obj) {

    $(".shop-tab-con-item").each(function (val) {
        Controller.Slider({
            father: $(this),
            container: ".shop-goods-list ul",
            prevBtn: ".shop-left-nav",
            nextBtn: ".shop-right-nav",
            itemSelector: "li",
            fatherSize: 1440
        });
    });
};
goodsDetail.methods.chooseSize = function (obj) {
    $(".shop-goods-size .shop-size-item").off("click").on("click", function () {
        $(this).addClass("shop-active").siblings(".shop-size-item").removeClass("shop-active");
    });
}
goodsDetail.methods.chooseNum = function (obj) {
    //数量减
    $(".shop-num-group .shop-num-substract").off("click").on("click", function () {
        if ($(this).hasClass("shop-disable")) {
            return;
        }
        var _val = $(this).siblings(".shop-num-input").val();
        var reg = /^[0-9]*$/;
        if (!reg.test(_val)) {
            _val = _val.replace(/[^0-9]/ig, "");
            $(this).siblings(".shop-num-input").val(_val);
            return;
        }
        var minNum = $(this).siblings(".shop-num-input").attr("data-min") | 0;
        var maxNum = $(this).siblings(".shop-num-input").attr("data-max") | 0;
        _val--;
        $(this).siblings(".shop-num-input").val(_val);
        goodsDetail.methods.numVal(_val, $(this).siblings(".shop-num-input"), minNum, maxNum);
    });
    //数量加
    $(".shop-num-group .shop-num-add").off("click").on("click", function () {
        if ($(this).hasClass("shop-disable")) {
            return;
        }
        var _val = $(this).siblings(".shop-num-input").val();
        var reg = /^[0-9]*$/;
        if (!reg.test(_val)) {
            _val = _val.replace(/[^0-9]/ig, "");
            $(this).siblings(".shop-num-input").val(_val);
            return;
        }
        var minNum = $(this).siblings(".shop-num-input").attr("data-min") | 0;
        var maxNum = $(this).siblings(".shop-num-input").attr("data-max") | 0;
        _val++;
        $(this).siblings(".shop-num-input").val(_val);
        goodsDetail.methods.numVal(_val, $(this).siblings(".shop-num-input"), minNum, maxNum);
    });
    //数量状态跟踪
    $(".shop-num-group .shop-num-input").off("input").on("input", function () {
        var _val = $(this).val();
        var reg = /^[0-9]*$/;
        if (!reg.test(_val)) {
            //截取，
            _val = _val.replace(/[^0-9]/ig, "");
            $(this).val(_val);
            return;
        }
        var minNum = $(this).attr("data-min") | 0;
        var maxNum = $(this).attr("data-max") | 0;
        goodsDetail.methods.numVal(_val, $(this), minNum, maxNum);
    });
}
//数量控制v
goodsDetail.methods.numVal = function (obj, cur, minNum, maxNum) {
    var _val = obj;
    if (obj) {
        //如果小于零，减禁用
        if (_val < minNum) {
            cur.val(minNum);
            cur.siblings(".substract").addClass("shop-disable");
        } else {
            cur.siblings(".substract").removeClass("shop-disable");
        }
        //如果，大于在售数，加禁用
        if (maxNum != 0 && _val > maxNum) {
            cur.siblings(".shop-num-add").addClass("shop-disable");
            cur.val(maxNum);
        } else {
            cur.siblings(".shop-num-add").removeClass("shop-disable");
        }
    } else {
        cur.val(minNum);
    }
}
//购物加入动画
goodsDetail.methods.FlyCartInit = function (obj) {
    $(".shop-goods-addCart").click(function (event) {
        var addcar = $(this);
        var dtop = $(document).scrollTop();
        var offset = $(".shop-top .shop-top-menu .shop-icon-cart").offset();
        event.preventDefault();
        var img = $(".shop-goods-info .shop-goods-images").find('img').attr('src');
        var flyer = $('<img width="100" height="100" class="shop-img-flyer" src="' + img + '">');
        flyer.fly({
            start: {
                left: event.pageX, //开始位置（必填）#fly元素会被设置成position: fixed
                top: (event.pageY - dtop) //开始位置（必填）
            },
            end: {
                left: offset.left + 10, //结束位置（必填）
                top: (offset.top + 10 - dtop), //结束位置（必填）
                width: 0, //结束时宽度
                height: 0 //结束时高度
            },
            onEnd: function () { //结束回调
                //购物车数量加
                this.destory();
                goodsDetail.methods.OverAddCart(this);
            }
        });
    });
}

//购物车添加动画，完成回调
goodsDetail.methods.OverAddCart = function (obj) {

}
//选择城市
goodsDetail.methods.ChooseCity = function (obj) {
    $(".shop-goods-delivery .shop-city-choose .shop-city-text").off("click").on("click", function () {
        var cityGroup = $(this).siblings(".shop-city-group");
        var overBox = cityGroup.find(".shop-choosed");
        var itemBox = cityGroup.find(".shop-city-con");
        //初始化，城市选择
        var citydata = cityData3;
        var itemHtml = "";
        //所有盒子
        overBox.children().remove();
        itemBox.children().remove();
        //填充默认省
        overBox.append('<div class="shop-choosed-item" data-type="0">请选择省</div>');
        $.each(citydata, function (key, val) {
            itemHtml += '<div data-id="' + val.value + '" data-index = "' + key + '" data-type="1" class="shop-city-item">' + val.text + '</div>';
        });
        itemBox.append(itemHtml);
        cityGroup.toggle();
        //加载事件
        goodsDetail.methods.CityEvent();
    });
}

goodsDetail.methods.CityEvent = function () {
    //省选择
    $(".shop-city-item[data-type=1]").off("click").on("click", function (e) {
        e.stopPropagation();
        var cityid = $(this).attr("data-id");
        var cname = $(this).text();
        var dataIndex = $(this).attr("data-index");
        var children = cityData3[dataIndex].children;
        //显示省
        var itemBox = $(this).parents(".shop-city-con");
        var overBox = itemBox.parents(".shop-city-group").find(".shop-choosed");
        overBox.html("");
        overBox.append('<div class="shop-choosed-item" data-type="1" data-id="' + cityid + '" data-index="' + dataIndex + '">' + cname + '</div>');
        if (children && children.length > 0) {
            //显示省下的区县
            var itemHtml = "";
            $.each(children, function (key, val) {
                itemHtml += '<div data-id="' + val.value + '" data-index = "' + key + '" data-type="2" class="shop-city-item">' + val.text + '</div>';
            });
            itemBox.html("");
            itemBox.append(itemHtml);
            //事件重绑定
            goodsDetail.methods.CityEvent();
        } else {
            var namestr = "";
            //汇总名称
            $(".shop-goods-delivery .shop-choosed").each(function () {
                namestr += $(this).text();
            });
            //显示
            $(".shop-goods-delivery .shop-city-choose .shop-city-text").text(namestr);
            //隐藏框
            $(this).parents(".shop-city-group").hide();
        }
    });
    //市选择
    $(".shop-city-item[data-type=2]").off("click").on("click", function (e) {
        e.stopPropagation();
        var cityid = $(this).attr("data-id");
        var cname = $(this).text();
        var sindex = $(".shop-choosed-item[data-type=1]").attr("data-index") | 0;
        var dataIndex = $(this).attr("data-index");
        var children = cityData3[sindex].children[dataIndex].children;
        //显示省
        var itemBox = $(this).parents(".shop-city-con");
        var overBox = itemBox.parents(".shop-city-group").find(".shop-choosed");
        var overHtml = overBox.html();
        overBox.html("");
        overBox.append(overHtml + '<div class="shop-choosed-item" data-type="2" data-id="' + cityid + '" data-index="' + dataIndex + '">' + cname + '</div>');
        if (children && children.length > 0) {
            //显示市下的区县
            var itemHtml = "";
            $.each(children, function (key, val) {
                itemHtml += '<div data-id="' + val.value + '" data-index = "' + key + '" data-type="3" class="shop-city-item">' + val.text + '</div>';
            });
            itemBox.html("");
            itemBox.append(itemHtml);
            //事件重绑定
            goodsDetail.methods.CityEvent();
        } else {
            var namestr = "";
            //汇总名称
            $(".shop-goods-delivery .shop-choosed").each(function () {
                namestr += $(this).text();
            });
            //显示
            $(".shop-goods-delivery .shop-city-choose .shop-city-text").text(namestr);
            //隐藏框
            $(this).parents(".shop-city-group").hide();
        }

    });
    //区县选择
    $(".shop-city-item[data-type=3]").off("click").on("click", function (e) {
        e.stopPropagation();
        var cityid = $(this).attr("data-id");
        var cname = $(this).text();
        var namestr = "";
        //汇总名称
        $(".shop-goods-delivery .shop-choosed").each(function () {
            namestr += $(this).text();
        });
        namestr += cname;
        //显示
        $(".shop-goods-delivery .shop-city-choose .shop-city-text").text(namestr);
        //隐藏框
        $(this).parents(".shop-city-group").hide();
    });
    //重选省份
    $(".shop-choosed-item[data-type=1]").off("click").on("click", function (e) {
        e.stopPropagation();
        var cityGroup = $(this).parents(".shop-city-group");
        var overBox = cityGroup.find(".shop-choosed");
        var itemBox = cityGroup.find(".shop-city-con");
        //初始化，城市选择
        var citydata = cityData3;
        var itemHtml = "";
        //所有盒子
        overBox.children().remove();
        itemBox.children().remove();
        //填充默认省
        overBox.append('<div class="shop-choosed-item" data-type="0">请选择省</div>');
        $.each(citydata, function (key, val) {
            itemHtml += '<div data-id="' + val.value + '" data-index = "' + key + '" data-type="1" class="shop-city-item">' + val.text + '</div>';
        });
        itemBox.append(itemHtml);
        //加载事件
        goodsDetail.methods.CityEvent();
    });
    //重选市
    $(".shop-choosed-item[data-type=2]").off("click").on("click", function (e) {
        e.stopPropagation();
        var cityGroup = $(this).parents(".shop-city-group");
        var overBox = cityGroup.find(".shop-choosed");
        var itemBox = cityGroup.find(".shop-city-con");
        var dataIndex = $(this).siblings("[data-type=1]").attr("data-index");
        var overHtml = $(this).siblings("[data-type=1]");
        var children = cityData3[dataIndex].children;
        //显示省
        overBox.html("");
        overBox.append(overHtml);
        //显示省下的区县
        var itemHtml = "";
        $.each(children, function (key, val) {
            itemHtml += '<div data-id="' + val.value + '" data-index = "' + key + '" data-type="2" class="shop-city-item">' + val.text + '</div>';
        });
        itemBox.html("");
        itemBox.append(itemHtml);
        //事件重绑定
        goodsDetail.methods.CityEvent();
    });
}
//选择支付方式
goodsDetail.methods.choosePay = function (obj) {
    $(".shop-pay .shop-pay-way").click(function (e) {
        $(this).addClass("shop-active").siblings(".shop-pay-way").removeClass("shop-active");
    });
}
//放大镜效果
goodsDetail.methods.ScaleImage = function (obj) {
    $(".shop-goods-images").mouseenter(function (e) {
        $(".shop-goods-inner").show(100);
        $(".shop-goods-big").show(100);
    });
    $(".shop-goods-images").mouseleave(function (e) {
        $(".shop-goods-inner").hide(100);
        $(".shop-goods-big").hide(100);
    });

    $(".shop-goods-images").mousemove(function (e) {
        // console.log(e.clientX);
        // console.log( $(".shop-goods-images").offset().left );
        var l = e.pageX - $(".shop-goods-images").offset().left - $(".shop-goods-inner").outerWidth() / 2;
        var t = e.pageY - $(".shop-goods-images").offset().top - $(".shop-goods-inner").outerHeight() / 2;
        var minL = 0,
            minT = 0;
        var maxL = $(".shop-goods-images").outerWidth() - $(".shop-goods-inner").outerWidth();
        var maxT = $(".shop-goods-images").outerHeight() - $(".shop-goods-inner").outerHeight();
        l = l <= minL ? 0 : (l >= maxL ? maxL : l);
        t = t <= minT ? 0 : (t >= maxT ? maxT : t);
        $(".shop-goods-inner").css({
            left: l,
            top: t
        });
        // $(".shop-goods-inner").css("margin-left",x);
        // $(".shop-goods-inner").css("margin-top",-465+y);
        $(".shop-goods-big>img").css({
            marginLeft: -3 * l,
            marginTop: -3 * t
        });
    });
    $(".shop-scrollWrap li").hover(function () {
        var imgSrc = $(this).find("img").attr('big-img');
        $(".shop-goods-images > img").attr("src", imgSrc);
        $(this).addClass("shop-img-hover").siblings().removeClass("shop-img-hover");
        $(".shop-goods-big > img").attr("src", imgSrc);
    })

    $(".picScroll").slide({
        mainCell: ".picList",
        effect: "left",
        vis: 5,
        pnLoop: false,
        scroll: 1,
        autoPage: true
    });

}

// 关注
goodsDetail.methods.isfocus = function(){
    $(".shop-share-box").on("click",".shop-focus",function(){
        $(this).toggleClass("shop-focus-click");
    })
}

// 关注店铺
goodsDetail.methods.isStore = function () {
    var flag = true;
    $(".shop-store-focus-btn").on("click","a",function () {
       if($(this).hasClass("shop-store-focus-click")){
            $(this).removeClass("shop-store-focus-click").text("关注店铺");
       }else{
            $(this).addClass("shop-store-focus-click").text("已关注");
       }
    })
}

//详情，内容栏目导航
goodsDetail.methods.DetailNav = function (obj) {
    $(".shop-user-choose ul li").off("click").on("click", function (e) {
        var navitem = $(this).attr("shop-nav");
        var sTop = $(".shop-temp[shop-nav=" + navitem + "]").offset().top;
        $("html,document").animate({
            scrollTop: sTop
        });
    });
}

// 评论图片切换
goodsDetail.methods.PictureSwitching = function (obj) {
    $(".shop-items").on("click", ".shop-evaluation .shop-img", function () {
        if ($(this).hasClass("shop-img-selected")) {
            $(this).removeClass("shop-img-selected");
        } else {
            $(this).parents(".shop-item .shop-right").find(".shop-img").each(function () {
                $(this).removeClass("shop-img-selected");
            });
            $(this).addClass("shop-img-selected");
        }
        goodsDetail.methods.UpdateBigimg($(this));
    });
}

// 更新大图路径
goodsDetail.methods.UpdateBigimg = function (obj) {
    var imgSelected = obj.parents(".shop-item .shop-right").find(".shop-img-selected");
    var bigImg = obj.parents(".shop-item .shop-right").find(".shop-big-img");
    if (imgSelected.length == 1) {
        bigImg.css("display", "block")
        bigImg.find("img").attr("src", imgSelected.find("img").attr("src"));
    } else {
        bigImg.css("display", "none")
    }
}
//追评下拉显示
goodsDetail.methods.chasingDown = function () {
    $(".shop-chasing-down").on("click", function () {
        $(this).toggleClass("shop-chasing-down2").parents(".shop-star").siblings(".shop-reviews-w").toggle();
        $(this).parents(".shop-star").siblings(".shop-review-text-box").hide().val("");
    })
}
// 追评回复

goodsDetail.methods.reviewComment = function () {
    $(".shop-review button").on("click", function () {
        $(this).parents(".shop-reviews-w").siblings(".shop-review-text-box").show();
    });
}

// 分页
goodsDetail.methods.pagination = function () {
    var page = new Controller.PageControl();
    page.init({
        totalCount: 100,
        conter: ".shop-pagination",
        nowPage: 1
    });
}


//添加购物车
goodsDetail.methods.AddCart = function (WaresID, SkuID, buyNum) {
    if (Cookie.getCookie("userid") != null && Cookie.getCookie("userid") != "") {
        //登录的情况
        $.post("/WaresOnlineArea/ShoppingCarts/AddNewShopCart", {
            UserID: Cookie.getCookie("userid"),
            waresOnlineID: WaresID,
            skuID: SkuID,
            buyNum: buyNum
        }, function (d) {
            if (d == 1 || d == 2) {
                //alert("添加成功!!!");
                // Refresh.refreshShoppingCartCount();
                //更新购物车展示数量
                $.post("/WaresOnlineArea/ShoppingCarts/GetShoppingCartQuantityAsync", {
                    UserID: Cookie.getCookie("userid"),
                }, function (count) {
                    $("#shop-Count").html(count);
                });
            } else {
                //alert("添加失败!!!");
            }
        });
    } else {
        //未登录情况
        var cookie = Cookie.getCookie('TempShoppingCart');
        var _tempShoppingCart = JSON.parse(cookie == '' ? '[]' : cookie);
        var waresid = parseInt(WaresID);
        var skuid = parseInt(SkuID); //这里未判断Sku选取的情况
        var canset = true;
        console.log(_tempShoppingCart);
        $.each(_tempShoppingCart, function (n, e) {
            if (e.waresid == waresid && e.skuid == skuid) {
                e.buyNum += parseInt($(".shop-num-input").val());
                canset = false;
            }
        });
        if (canset) {
            //添加
            var newtempProd = new Object();
            newtempProd.waresid = waresid;
            newtempProd.skuid = skuid;
            newtempProd.buyNum = buyNum;
            _tempShoppingCart.push(newtempProd);
        }
        //重新设置
        Cookie.setCookie('TempShoppingCart', JSON.stringify(_tempShoppingCart), 7);
        GetCount();
        //刷新数量
        $('#shop-item-count').text(_tempShoppingCart.length);
    }
};




